const route = require('koa-router')();
const axios = require('axios');
const qs = require('qs');

const url = require('../../config');

axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded';
axios.defaults.transformRequest = function (data: any) {
    return qs.stringify(data);
};

// 暂时使用
function login(session: any, info: any) {
    session.user = {
        ...info
    }
}

// 用户登录
route.post('/api/login', async function (ctx: any, next: any) {
    const { email, password, checked } = ctx.request.body;
    await axios
        .post(`${url.apiBaseUrl}/web/login`, {
            email,
            password,
        })
        .then((res: any) => {
            const { code, data } = res.data;
            if (code == 1000) {
                // 暂时使用
                let objData = Object.assign(data, {
                    checked: checked
                });
                login(ctx.session, objData);
            }
            ctx.body = res.data;
        }).catch((error: any) => {
            let data = {
                code: 1001,
                msg: '服务器异常',
                data: {}
            }
            ctx.body = data;
            console.log(error);
        })
});


// 用户使用邮箱登录
route.post('/api/login/email', async function (ctx: any, next: any) {
    const { email, code } = ctx.request.body;
    await axios
        .post(`${url.apiBaseUrl}/web/login/email`, {
            email,
            code,
        })
        .then((res: any) => {
            const { code, data } = res.data;
            if (code == 1000) {
                login(ctx.session, data);
            }
            ctx.body = res.data;
        }).catch((error: any) => {
            let data = {
                code: 1001,
                msg: '服务器异常',
                data: {}
            }
            ctx.body = data;
            console.log(error);
        })
});

// 用户退出
route.post('/api/logout', async function (ctx: any, next: any) {
    const { guid, token } = ctx.request.body;

    await axios
        .post(`${url.apiBaseUrl}/web/login`, {
            guid,
            token,
        })
        .then((res: any) => {
            const data = {
                code: 1000,
                msg: '成功退出',
                data: {}
            };

            ctx.body = data;
            ctx.session = null;
        })
});

module.exports = route;
